#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define N 5 

void Runchild()
{
    printf("I am child,pid:%d,ppid:%d\n",getpid(),getppid());
    sleep(10);
}

int main2()
{
    for(int i = 0;i<N;i++)
    {
        pid_t id = fork();
        if(id == 0)
        {
            Runchild();
            exit(0);
        }
        printf("create child process: %d success\n",id);
        sleep(1);
    }

    sleep(20);

    // 多进程等待场景
    for(int i = 0;i<N;i++)
    {
        int wstatus = 0;
        pid_t id = waitpid(-1,&wstatus,WNOHANG);
        if(id > 0)
        {
            printf("wait %d success\n", id);
        }
    }

    sleep(10);

    return 0;
}

int main()
{
    pid_t id = fork();
    if(id < 0)
    {
        perror("fork");
        return 1;
    }
    else if(id == 0)
    {
        int cnt = 5;
        while(cnt)
        {
            printf("I am child, pid:%d, ppid:%d, cnt: %d\n", getpid(), getppid(), cnt);
            cnt--;
            sleep(1);
        }
        exit(1);
    }
    else
    {
        while(1)
        {
            int status = 0;
            pid_t ret = waitpid(-1,&status,0);
            if(ret == 0)
            {
                printf("waiting~,ret:%d\n",ret);
                sleep(1);
            }
            else if(WIFEXITED(status) && ret == id)
            {
                printf("waitpid sucess, this is exitcode is %d\n",WEXITSTATUS(status));
                // break;
            }
            else
            {
                perror("waitpid");
                break;
            }
        }
    }
    return 0;
}